import type { UnwrapNestedRefs } from 'vue';
import type { CardQueryParams, CardSearchHistoryDelete } from '/@/api/general/model/cardModel';
import { defineComponent, reactive, ref, unref, watchEffect } from 'vue';
import { useVModels } from '@vueuse/core';
import { useUserStore } from '/@/store/modules/user';
import { isEqual, trim } from 'lodash-es';
import { Icon as VIcon } from 'vant';
import { awaitWrap } from '/@/utils';
import { CardAssociativeWordApi, CardDeleteHistoryApi, CardSearchHistoryApi } from '/@/api/general/card';

import('./SearchHistory.less');

export default defineComponent({
  name: 'SearchHistory',
  props: {
    show: {
      type: Boolean as PropType<boolean>,
      required: true,
      default: () => {
        return false;
      },
    },
    areaHeight: {
      type: Number as PropType<number>,
      required: true,
      default: () => {
        return 0;
      },
    },
    gameId: {
      type: String as PropType<string>,
      required: true,
    },
    queryParams: {
      type: Object as PropType<UnwrapNestedRefs<CardQueryParams>>,
      required: true,
    },
  },
  emits: ['update:show', 'setQueryParamsName'],
  setup(props, { emit }) {
    // 设置分享参数
    const { show } = useVModels(props, emit);
    const userStore = useUserStore();

    // 输入的内容
    const queryName = ref<string>('');
    queryName.value = props.queryParams.name!;

    // 是否为联想结果
    const isLenovo = ref(true);

    // 数据
    const listData = reactive<string[]>([]);

    // 查询历史记录
    const getHistory = async () => {
      listData.length = 0;
      if (!userStore.getToken) {
        return;
      }
      console.log('getHistory');
      const [error, result] = await awaitWrap(CardSearchHistoryApi({ game_id: props.gameId }));
      if (error || !result) {
        return;
      }
      result.history_words.map((text) => {
        listData.push(text);
      });
    };

    // 查询联想结果
    const getLenovo = async () => {
      console.log('change' + props.queryParams.name);
      listData.length = 0;
      const [error, result] = await awaitWrap(
        CardAssociativeWordApi({ game_id: props.gameId, search_key: props.queryParams.name! })
      );
      if (error || !result) {
        return;
      }
      result.associative_words.map((text) => {
        listData.push(text);
      });
    };

    // 删除历史记录
    const deleteHistory = async (history_word: string, delete_all: 0 | 1, index: number) => {
      const params: CardSearchHistoryDelete = {
        game_id: props.gameId,
      };
      if (delete_all) {
        params.delete_all = 1;
      } else {
        params.history_word = history_word;
      }
      const [error] = await awaitWrap(CardDeleteHistoryApi(params));
      if (error) {
        return;
      }
      if (delete_all) {
        listData.length = 0;
      } else {
        listData.splice(index!, 1);
      }
    };

    const getListData = (val: string, time: number) => {
      return setTimeout(() => {
        if (!trim(val)) {
          isLenovo.value = false;
          getHistory();
          return;
        }
        if (trim(val)) {
          isLenovo.value = true;
          getLenovo();
        }
      }, time);
    };

    // watchEffect防抖示例
    watchEffect((onCleanup) => {
      if (!show.value) {
        return;
      }
      const { queryParams } = props;
      if (isEqual(queryName.value, queryParams.name)) {
        return;
      }
      queryName.value = queryParams.name!;
      listData.length = 0;
      const timer = getListData(queryName.value, 500);
      // 清除副作用（防抖）
      onCleanup(() => clearTimeout(timer));
    });

    const ListArea = () => {
      return (
        <div>
          <ul>
            {listData.map((text, index) => {
              return (
                <li class={'flex pb-sm items-center'}>
                  <div
                    class={'flex-1 van-ellipsis'}
                    onClick={() => {
                      emit('setQueryParamsName', text);
                    }}
                  >
                    {text}
                  </div>
                  {!unref(isLenovo) ? (
                    <VIcon
                      name='cross'
                      color={'#afafaf'}
                      onClick={() => {
                        deleteHistory(text, 0, index);
                      }}
                    />
                  ) : null}
                </li>
              );
            })}
          </ul>
          {!unref(isLenovo) ? (
            <div
              class={'text-gray-500 text-sm'}
              onClick={() => {
                deleteHistory('', 1, -1);
              }}
            >
              清空历史
            </div>
          ) : null}
        </div>
      );
    };

    const HistoryContainer = () => {
      if (!show.value || !listData.length) {
        return null;
      }
      return (
        <div class={'search-history-container'} style={{ bottom: `${props.areaHeight + 2}px` }}>
          <ListArea />
        </div>
      );
    };

    return () => <HistoryContainer />;
  },
});
